package com.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.domain.Notice;
import com.domainVO.NoticeVO;
import com.domainVO.PageInfoVO;
import com.mapper.helping.NoticeMapper;
import com.mapper.living.UserDao;
import com.service.INoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.util.UserUtil;
import com.util.living.LivingQiNiuYunUtils;
import living.com.domain.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 大忽悠
 * @since 2022年02月12日
 */
@Service
@RequiredArgsConstructor
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {
    private final UserDao userDao;
    /**
     * <p>
     *     获取当前用户未读的所有通知,读取完后,删除所有未读通知
     * </p>
     * @return
     */
    @Override
    public Map<String, Object> iNoticeService(Integer startPage, Integer pageSize) {
        Page<Notice> page=new Page<>(startPage,pageSize);
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<Notice>().eq("to_user_id", UserUtil.getUserId());
        //获取所有未读通知
        List<Notice> noticeList = page(page,queryWrapper).getRecords();
        //获取完后,删除未读通知
        remove(queryWrapper);
        //包装后返回
        List<NoticeVO> noticeVOS = noticeList.stream().map(notice -> {
            NoticeVO noticeVO = NoticeVO.builder().fromUserId(notice.getFromUserId())
                    .toUserId(notice.getToUserId())
                    .eventId(notice.getEventId())
                    .type(notice.getType())
                    .issueId(notice.getIssueId())
                    .createTime(notice.getCreateTime()).build();
            //查询触发事件的用户姓名和头像
            User user = userDao.getUserById(notice.getFromUserId());
            noticeVO.setFromUserName(user.getUsername());
            noticeVO.setFromUserAvatar(user.getAvatar());
            return noticeVO;
        }).collect(Collectors.toList());
        return PageInfoVO.builder().autoWired(page,noticeVOS);
    }
}
